<template>
  <PerfectTableComponent
    :loadTableList="loadTableList"
    :changePageSize="changePageSize"
    :changePage="changePage"
    :removeQueryField="removeQueryField"
    :clearQuery="clearQuery"
    v-model:query="query"
    title="汽车订单模块"
    ref="tableRef"
    AddNewButtonText="模拟下订单"
    :queryFormHeaders="queryFormHeaders"
    :table="table"
    :tableColumns="tableColumns"
    :showTableIndex="false"
    :showDeleteButton="false"
    :operatorColumnWidth="300"
    :baseUrl="urls.API_URL_BACKSTAGE_SHOP_CARORDER"
    v-model:form="form"
    :formHeader="formHeader"
    @beforeAddRow="beforeAddRow"
    @beforeFormSubmit="beforeFormSubmit"
  >
    <!--所属汽车产品-->
    <template #table_column_carProductName="scope: any">
      {{ scope.row.carProduct != null ? scope.row.carProduct.name : '' }}
    </template>
    <!--所属车型配置-->
    <template #table_column_carModelConfigName="scope: any">
      {{ scope.row.carModelConfig != null ? scope.row.carModelConfig.name : '' }}
    </template>
    <!--所属账户-->
    <template #table_column_customerUsername="scope: any">
      {{ scope.row.customer != null ? scope.row.customer.username : '' }}
    </template>
    <!-----------------------------表格自定义列（操作列）----------------------------------------->
    <template #table_operator_right="scope">
      <el-dropdown
        v-if="scope.row.orderStatus !== 'cancelled' && scope.row.orderStatus !== 'completed'"
        placement="bottom-start"
        @command="handleOrderStatus($event, scope.row)"
        style="margin-left: 10px; margin-top: 1px"
      >
        <el-button type="primary" size="small" icon="Grid" plain>订单操作</el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <template v-if="scope.row.orderStatus == 'pending'">
              <el-dropdown-item command="paid">模拟支付</el-dropdown-item>
              <el-dropdown-item command="customerCancelled">客户取消订单</el-dropdown-item>
            </template>
            <el-dropdown-item v-if="scope.row.orderStatus == 'paid'" command="confirmed">商家确认订单</el-dropdown-item>
            <el-dropdown-item v-if="scope.row.orderStatus == 'paid' || scope.row.orderStatus == 'confirmed'" command="cancelled"
              >商家取消订单</el-dropdown-item
            >
            <el-dropdown-item v-if="scope.row.orderStatus == 'produced'" command="shipped">发货</el-dropdown-item>
            <el-dropdown-item v-if="scope.row.orderStatus == 'shipped'" command="completed">模拟客户收货</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </template>
  </PerfectTableComponent>
</template>

<script setup lang="ts">
import PerfectTableComponent from '@/components/base/table/PerfectTableComponent.vue';
import { onMounted, provide, reactive, ref } from 'vue';
import useTableList from '@/api/hooks/useTableList';
import type { FormHeader, ResponseData, TableColumn } from '@/types/interface/base_interface';
import urls from '@/api/request/urls';
import { getDict } from '@/api/dict';
import type { ShopCarOrder } from '@/types/interface/shop_interface';
import Request from '@/api/request/request';

// 表格工具必备参数
const { table, query, loadTableList, removeQueryField, clearQuery, changePageSize, changePage } = useTableList(urls.API_URL_BACKSTAGE_SHOP_CARORDER);
// 将表格刷新函数传到子容器
provide('loadTableList', loadTableList);

//查询==========================================================
const queryFormHeaders = ref<FormHeader[]>([]);

//表格==========================================================
// 表格插件ref对象
const tableRef = ref();

//表格列
// 定义表格所有的列字段信息
const tableColumns = ref<TableColumn[]>([]);

//表单==========================================================
//表单对象
const form = ref<ShopCarOrder>({});
//表单元素类型
const formHeader = ref<FormHeader[]>([]);

onMounted(async () => {
  //定义优先级选项。放在mounted中执行时，要将引用改变量的属性也放进来。
  const orderStatusDict = await getDict('汽车订单状态', 'string');
  queryFormHeaders.value = [
    // 查询表单
    {
      prop: 'orderStatus',
      label: '订单状态',
      type: 'select',
      list: orderStatusDict
    },
    {
      prop: 'customer.id',
      label: '账户名',
      type: 'selectRemote',
      url: urls.API_URL_BACKSTAGE_SHOP_CUSTOMER_USERNAME,
      queryNameForUrl: 'username',
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: '{username}（{name}）'
        }
      }
    },
    {
      prop: 'deliveryName',
      label: '客户姓名'
    },
    {
      prop: 'deliveryTel',
      label: '客户电话'
    },
    {
      prop: 'deliveryZip',
      label: '客户邮编'
    },
    {
      prop: 'createTimeQueryBetween',
      propAsNames: ['createTimeQueryOfBegin', 'createTimeQueryOfEnd'],
      label: '下单时间',
      type: 'daterange',
      show: true,
      width: '300px'
    }
  ];
  //表格对象
  tableColumns.value = [
    {
      label: '产品名',
      prop: 'carProductName',
      width: 250,
      type: 'custom',
      fixed: true
    },
    {
      label: '车型配置',
      prop: 'carModelConfigName',
      type: 'custom',
      width: 200
    },
    {
      label: '订单状态',
      prop: 'orderStatus',
      width: 100,
      type: 'dict',
      dict: orderStatusDict,
      config: {
        dictTag: {
          primary: ['completed'],
          success: ['producing'],
          danger: ['cancelled']
        }
      }
    },
    // {
    //   label: '订单状态',
    //   prop: 'orderStatus',
    //   type: 'dict',
    //   dict: orderStatusDict,
    //   width: 200
    // },
    {
      label: '客户账户名',
      prop: 'customerUsername',
      type: 'custom',
      width: 120
    },
    {
      label: '客户姓名',
      prop: 'deliveryName',
      width: 100
    },
    {
      label: '客户电话',
      prop: 'deliveryTel',
      width: 120
    },
    {
      label: '客户地址',
      prop: 'deliveryAddress',
      width: 200
    },
    {
      label: '客户邮编',
      prop: 'deliveryZip',
      width: 120
    },
    {
      label: '创建时间',
      prop: 'createTime',
      width: 180
    },
    {
      label: '最后编辑时间',
      prop: 'updateTime',
      width: 180
    }
  ];
  // 添加编辑表单
  formHeader.value = [
    {
      prop: 'customerId',
      label: '客户',
      type: 'selectRemote',
      action: 'post',
      width: '300px',
      url: urls.API_URL_BACKSTAGE_SHOP_CUSTOMER_USERNAME,
      queryNameForUrl: 'username',
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: '{username}（{name}）'
        }
      },
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      prop: 'carProductId',
      label: '汽车产品',
      type: 'selectRemote',
      action: 'post',
      width: '300px',
      url: urls.API_URL_BACKSTAGE_SHOP_CARPRODUCT,
      queryNameForUrl: 'name',
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: '{name}'
        }
      },
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '姓名',
      prop: 'deliveryName',
      action: 'put',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 20,
          message: '长度在 2 到 20个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '电话',
      prop: 'deliveryTel',
      action: 'put',
      rules: [{ pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码' }]
    },
    {
      label: '地址',
      prop: 'deliveryAddress',
      action: 'put',
      rules: [
        {
          max: 100,
          message: '长度不超过100个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '邮编',
      prop: 'deliveryZip',
      action: 'put',
      rules: [{ pattern: /^[0-9]{6}$/, message: '请输入正确的邮编格式' }]
    },
    // {
    //   label: '订单状态',
    //   prop: 'orderStatus',
    //   action: 'put',
    //   type: 'select',
    //   list: orderStatusDict,
    //   rules: [
    //     {
    //       required: true,
    //       message: '不能为空',
    //       trigger: 'blur'
    //     }
    //   ]
    // },
    {
      label: '备注',
      prop: 'remark',
      type: 'textarea',
      rules: [
        {
          max: 255,
          message: '长度不超过255个字符',
          trigger: 'blur'
        }
      ]
    }
  ];
});
//在添加行的动作以前
const beforeAddRow = async () => {
  //传入初始值
};
//在表单提交前对对象进行封装
const beforeFormSubmit = () => {
  if (form.value.customerId != null) {
    form.value.customer = {
      id: form.value.customerId
    };
  }
  if (form.value.carProductId != null) {
    form.value.carProduct = {
      id: form.value.carProductId
    };
  }
};
//操作订单下拉框
const handleOrderStatus = async (command: string | number | object, carOrder: ShopCarOrder) => {
  // 读取修改订单状态
  const resData: any = await new Request(`${urls.API_URL_BACKSTAGE_SHOP_CARORDER}/${carOrder.id}/status`, null, {
    params: { targetStatus: command }
  }).patch();
  if (resData.success) {
    loadTableList();
  }
};
</script>

<style scoped></style>
